package com.cypher.encryptionanddecryption.fragment.protocol.kunlun;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.fragment.protocol.AbstractProtocolFragment;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.KunLunProtocolUtils;
import com.cypher.encryptionanddecryption.util.VariableUtils;
import com.cypher.encryptionanddecryption.watcher.DecimalDigitsWatcher;

import org.apache.commons.lang3.StringUtils;

/**
 * 参数页面
 * @author: 古霸天
 * @date: 2020/12/25
 */
public class ParamFragment extends AbstractProtocolFragment {
    /**
     * 定时上传周期值
     */
    private EditText text1;
    /**
     * 定时上传时间点
     */
    private EditText text2;
    /**
     * 一级多天不用气关阀门限
     */
    private EditText text3;
    /**
     * 二级多天不用气关阀门限
     */
    private EditText text4;
    /**
     * 多天不通信关阀参数
     */
    private EditText text5;
    /**
     * 错峰系数
     */
    private EditText text6;
    /**
     * 最大预留量
     */
    private EditText text7;

    /**
     * IPV4地址
     */
    private Spinner spinner1;
    /**
     * 定时上传周期类型
     */
    private Spinner spinner2;
    /**
     * 过流报警关阀使能
     */
    private Spinner spinner3;
    /**
     * 过流门限
     */
    private Spinner spinner4;
    /**
     * 微小流量报警使能
     */
    private Spinner spinner5;

    private final String[] spinner1Arr = {"测试", "正式"};
    private final String[] spinner2Arr = {"天", "月"};
    private final String[] spinner3Arr = {"禁用", "启用"};
    private final String[] spinner4Arr = {"G1.6", "G2.5", "G4"};

    private final String[] spinner1ArrContent = {"B4659373", "753C9D89"};
    private final String[] spinner2ArrContent = {"00", "01"};
    private final String[] spinner4ArrContent = {"30", "48", "72"};
    /**
     * 操作对象
     */
    private CommunicationBean bean;
    private BluetoothCommunicationActivity activity;
    public ParamFragment(BluetoothCommunicationActivity activity, CommunicationBean bean) {
        this.activity = activity;
        this.bean = bean;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_kunlun_param, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    /**
     * 初始化页面
     * @param view
     */
    private void init(View view) {
        // 定义输入框过滤器
        InputFilter[] inputFilters2 = new InputFilter[1];
        inputFilters2[0] = new InputFilter.LengthFilter(2);

        InputFilter[] inputFilters3 = new InputFilter[1];
        inputFilters3[0] = new InputFilter.LengthFilter(3);

        InputFilter[] inputFilters4 = new InputFilter[1];
        inputFilters4[0] = new InputFilter.LengthFilter(4);

        text1 = view.findViewById(R.id.text1);
        text1.setInputType(InputType.TYPE_CLASS_NUMBER);
        text1.setFilters(inputFilters2);

        text2 = view.findViewById(R.id.text2);
        text2.setInputType(InputType.TYPE_CLASS_NUMBER);
        text2.setFilters(inputFilters4);

        text3 = view.findViewById(R.id.text3);
        text3.setInputType(InputType.TYPE_CLASS_NUMBER);
        text3.setFilters(inputFilters2);

        text4 = view.findViewById(R.id.text4);
        text4.setInputType(InputType.TYPE_CLASS_NUMBER);
        text4.setFilters(inputFilters2);

        text5 = view.findViewById(R.id.text5);
        text5.setInputType(InputType.TYPE_CLASS_NUMBER);
        text5.setFilters(inputFilters2);

        text6 = view.findViewById(R.id.text6);
        text6.setInputType(InputType.TYPE_CLASS_NUMBER);
        text6.setFilters(inputFilters2);

        text7 = view.findViewById(R.id.text7);
        text7.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        text7.setFilters(inputFilters3);
        text7.addTextChangedListener(new DecimalDigitsWatcher(text7, 2));

        ArrayAdapter adapter1 = new ArrayAdapter<String>(view.getContext(), R.layout.spinner_item, spinner1Arr);
        adapter1.setDropDownViewResource(R.layout.dropdown_stytle);
        ArrayAdapter adapter2 = new ArrayAdapter<String>(view.getContext(), R.layout.spinner_item, spinner2Arr);
        adapter2.setDropDownViewResource(R.layout.dropdown_stytle);
        ArrayAdapter adapter3 = new ArrayAdapter<String>(view.getContext(), R.layout.spinner_item, spinner3Arr);
        adapter3.setDropDownViewResource(R.layout.dropdown_stytle);
        ArrayAdapter adapter4 = new ArrayAdapter<String>(view.getContext(), R.layout.spinner_item, spinner4Arr);
        adapter4.setDropDownViewResource(R.layout.dropdown_stytle);

        spinner1 = view.findViewById(R.id.spinner1);
        spinner1.setAdapter(adapter1);
        spinner1.setSelection(1);

        spinner2 = view.findViewById(R.id.spinner2);
        spinner2.setAdapter(adapter2);
        spinner2.setSelection(0);

        spinner3 = view.findViewById(R.id.spinner3);
        spinner3.setAdapter(adapter3);
        spinner3.setSelection(1);

        spinner4 = view.findViewById(R.id.spinner4);
        spinner4.setAdapter(adapter4);
        spinner4.setSelection(1);

        spinner5 = view.findViewById(R.id.spinner5);
        spinner5.setAdapter(adapter3);
        spinner5.setSelection(0);

    }

    @Override
    public void fillFragment(String data) {
        text1.setText(""); text2.setText(""); text3.setText(""); text4.setText("");
        text5.setText(""); text6.setText(""); text7.setText("");
        spinner1.setSelection(0); spinner2.setSelection(0); spinner3.setSelection(0);
        spinner4.setSelection(0); spinner5.setSelection(0);
        activity.getHandler().postDelayed(() -> {
            String formatData = KunLunProtocolUtils.formatReceiveData(data);
            renderParam(formatData.substring(6));
        }, 200);

    }
    /**
     * 根据接收数据渲染昆仑协议参数
     * @param data
     * @return
     */
    private void renderParam(String data) {
        spinner1.setSelection(VariableUtils.getIndexByArray
                (spinner1ArrContent, data.substring(14, 22)));
        spinner2.setSelection(VariableUtils.getIndexByArray
                (spinner2ArrContent, data.substring(118, 120)));
        text1.setText(String.valueOf(Integer.parseInt(
                StringUtils.substring(data, 120, 122), 16)));
        text2.setText(StringUtils.substring(data, 122, 126));
        text3.setText(String.valueOf(Integer.parseInt(
                StringUtils.substring(data, 126, 128), 16)));
        text4.setText(String.valueOf(Integer.parseInt(
                StringUtils.substring(data, 128, 130), 16)));
        text5.setText(String.valueOf(Integer.parseInt(
                StringUtils.substring(data, 130, 132), 16)));
        spinner3.setSelection(VariableUtils.getIndexByArray
                (spinner2ArrContent, data.substring(132, 134)));
        spinner4.setSelection(VariableUtils.getIndexByArray
                (spinner4ArrContent, String.valueOf(Integer.parseInt
                        (data.substring(134, 138), 16))));
        text6.setText(String.valueOf(Integer.parseInt(
                StringUtils.substring(data, 138, 140), 16)));
        spinner5.setSelection(VariableUtils.getIndexByArray
                (spinner2ArrContent, data.substring(140, 142)));
        // 最大预留量
        double maximumReserve = (double)Integer.parseInt(StringUtils.substring
                (data, 142, 146), 16) / 100;
        text7.setText(String.format("%.2f", maximumReserve));
    }

    @Override
    public String getHexCode(String rwType) {
        // 如果是只读的，hex码从实体中取
        if (StringUtils.equals("read", rwType)) {
            return KunLunProtocolUtils.getKunLunSpecialCommand(bean.getHexCode());
        }
        // 如果是写数据，需要重新组包
        return  getWriteCode();
    }

    /**
     * 获取表号写入发送码
     * @return
     */
    private String getWriteCode() {
        String txt1 = text1.getText().toString().trim();
        String txt2 = text2.getText().toString().trim();
        String txt3 = text3.getText().toString().trim();
        String txt4 = text4.getText().toString().trim();
        String txt5 = text5.getText().toString().trim();
        String txt6 = text6.getText().toString().trim();
        String txt7 = text7.getText().toString().trim();
        if (VariableUtils.isEmpty(txt1, txt2, txt3, txt4, txt5, txt6, txt7)) {
            Toast.makeText(activity, "数据不能为空", Toast.LENGTH_SHORT).show();
            return VariableUtils.EMPTY;
        }
        if (txt2.length() != 4) {
            Toast.makeText(activity, "定时上传时间点长度必须为4", Toast.LENGTH_SHORT).show();
            return VariableUtils.EMPTY;
        }

        String data = "010001000100" + "00";

        data += spinner1ArrContent[spinner1.getSelectedItemPosition()];
        data += "00000000000000000000000000000000"
                + "1633"
                + "63746E620000000000000000000000000000000000000000000000000000";
        data += spinner2ArrContent[spinner2.getSelectedItemPosition()];
        data += HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(txt1)), 2);
        data += txt2;
        data += HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(txt3)), 2);
        data += HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(txt4)), 2);
        data += HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(txt5)), 2);
        data += spinner2ArrContent[spinner3.getSelectedItemPosition()];
        data += HexUtils.paddingLeft(Integer.toHexString
                (Integer.parseInt(spinner4ArrContent[spinner4.getSelectedItemPosition()])), 4);
        data += HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(txt6)), 2);
        data += spinner2ArrContent[spinner5.getSelectedItemPosition()];
        data += HexUtils.doubleToHex(Double.parseDouble(txt7), 2, 4);

        data = "00D68400"
                + HexUtils.paddingLeft(Integer.toHexString(data.length() / 2), 2)
                + data;
        data = HexUtils.paddingLeft(Integer.toHexString(data.length() / 2), 2) + data;
        return KunLunProtocolUtils.getKunLunCommand(KunLunProtocolUtils.conSelf + data);
    }

}
